package com.example.financeapi.config.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 实现WebMvcConfigurer接口配置拦截所有URl
 * @author Alvin
 */
@Configuration
public class ConfigurerAdapter implements WebMvcConfigurer {

    @Bean
    public AuthInterceptor jwtInterceptor(){
        return new AuthInterceptor();
    }

    @Bean
    public AccessLimitInterceptor accessLimitInterceptor(){
        return new AccessLimitInterceptor();
    }

    /**
     * 拦截所有路径
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtInterceptor()).addPathPatterns("/**")
                .excludePathPatterns(AuthInterceptor.patterns);
        registry.addInterceptor(accessLimitInterceptor()).addPathPatterns("/**")
                .excludePathPatterns(AuthInterceptor.patterns);
    }

    /**
     * 跨域支持
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS")
                .allowCredentials(true).maxAge(3600);
    }

    /**
     * 如果项目的一些资源文件放在/WEB-INF/resources/下面
     * 在浏览器访问的地址就是类似：https://host:port/projectName/WEB-INF/resources/xxx.css
     * 但是加了如下定义之后就可以这样访问：
     * http://flycatzly.natapp1.cc/static/MP_verify_ltIzExudE8myPMpV.txt
     * 非必须
     */
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/resources/**")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");

    }
}